#include "serial1_fun.h"
#include <Arduino.h>
#include <nvs_flash.h>
#include "common_util.h"

// 串口2波特率
uint32_t Serial1BaudRate = 115200;
char* Serial1_k3k4_BR_key = "S1BR_key";


void serial1Init() {
  Serial.print("Serial1:");
  if (disableSerial1) {
    Serial.print("OFF");
  } else {
    Serial.print("NO");
  }
  Serial.println("  S1_E0  S1_E1");

  // 读取串口2波特率
  nvs_get_u32(my_nvs_handle_t, Serial1_k3k4_BR_key, &Serial1BaudRate);

  Serial.print("Serial1BaudRate:");
  Serial.print(Serial1BaudRate);
  Serial.println("  S1_B115200  S1_B9600");
  // 如果功能没有开启，直接退出
  if (disableSerial1) {
    return;
  }
  Serial.println("init Serial1");
  if (obtp[3] >= 99 || obtp[3] < 0 || obtp[4] >= 99 || obtp[4] < 0) {
    Serial.print("Serial1 PIN error!");
  } else {
    Serial1.begin(Serial1BaudRate, SERIAL_8N1, obtp[3], obtp[4]);  // RX, TX
    Serial.print("Serial1 init ok!");
    xTaskCreatePinnedToCore(Serial1Task, "Serial1Task", 1024 * 10, NULL, 1, NULL, 0);
  }
  Serial.print("RX Pin:");
  Serial.print(obtp[3]);
  Serial.print(",TX Pin:");
  Serial.print(obtp[4]);
  Serial.print(",Baud Rate:");
  Serial.println(Serial1BaudRate);
}

void Serial1Task(void* ptParam) {
  while (1) {
    if (Serial1.available()) {
      String request = Serial1.readStringUntil('\n');
      if (!requestTest(request)) {
        continue;
      }
      String temp = "S1_IN_";
      temp.concat(request);
      broadcast(temp);
    }
  }
}

uint8_t requestS1(String request, int len) {
  if (!(request.startsWith("S1_") || request.startsWith("s1_"))) {
    return 0;
  }
  if (len < 5) {
    return 1;
  }
  char c3 = request.charAt(3);
  if (c3 == 'E' || c3 == 'e') {
    Serial.print("Set Serial1(Use k4 k5 pin):");
    if (request.charAt(4) == '1') {
      saveVlaueU8(Serial1_k3k4_key, 1);
      Serial.println("ON");
    } else {
      saveVlaueU8(Serial1_k3k4_key, 0);
      Serial.println("OFF");
    }
    return 1;
  }
  if (c3 == 'B' || c3 == 'b') {
    String ss = request.substring(4, len);
    uint32_t num = (uint32_t)(ss.toInt());
    if (num <= 0) {
      Serial.print("Serial1BaudRate error:");
      Serial.println(ss);
    } else {
      Serial.print("Set Serial1(Use k4 k5 pin) Serial1BaudRate:");
      saveVlaueU32(Serial1_k3k4_BR_key, num);
      Serial.println(num);
    }
    return 1;
  }
  // 如果功能没有禁用，且数据格式正确且正常
  if (!disableSerial1 && len >= 7 && (request.startsWith("S1_OUT_") || request.startsWith("s1_out_"))) {
    Serial1.println(request.substring(7, len));
    return 1;
  }
  return 1;
}